package com.xjw.hospital.utils;


import com.sun.mail.util.MailSSLSocketFactory;
import com.xjw.coreutil.exception.ServiceException;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @author 徐军文
 * @since 2022/8/26 23:55
 */
public final class EmailUtil {

    private static final String KEY = "zmyjtudbhaybchhj";

    private static final Properties props = new Properties();

    private static final String sender = "3486962680@qq.com";

    private static final Session session;

    static {
        try {
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置邮件服务器主机名
            props.setProperty("mail.host", "smtp.qq.com");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");
            props.put("mail.smtp.ssl.enable", "true");
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            props.put("mail.smtp.ssl.socketFactory", sf);
            session = Session.getInstance(props);
        } catch (Exception e) {
            throw new ServiceException("fail to init email util", e);
        }
    }

    public static void main(String[] args) throws Exception {
        String receiver = "18355093023@163.com";
        System.out.println(sendEmail("测试111", receiver));
    }

    public static boolean sendEmail(String content, String... receivers) {
        try {
            //邮件内容部分
            Message msg = new MimeMessage(session);
            msg.setSubject("抢票软件提醒");
            msg.setText(content);
            msg.setFlag(Flags.Flag.RECENT, true);
            //邮件发送者
            msg.setFrom(new InternetAddress(sender));
            //发送邮件
            Transport transport = session.getTransport();
            transport.connect("smtp.qq.com", sender, KEY);
            Address[] addresses = new Address[receivers.length];
            for (int i = 0;i < receivers.length;i++) {
                addresses[i] = new InternetAddress(receivers[i]);
            }
            transport.sendMessage(msg, addresses);
            transport.close();
            return true;
        } catch (MessagingException e) {
            return false;
        }
    }

}
